<template>
	<!--智能咨询页面-->
	<view class="consultation_page">
		<!-- 页面标题栏 -->
		<view class="page_header">
			<view class="title">咨询</view>
			<!-- 新建咨询按钮 -->
			<view class="new_consultation_btn" @click="createNewConsultation">
				<text class="btn_text">+</text>
			</view>
		</view>
		
		<scroll-view class="consultation_list" scroll-y>
			<block v-if="consultationList.length > 0">
				<view :key="index" v-for="(item,index) in consultationList" class="consultation_item"
					:data-index="index" @touchstart="drawStart($event)" @touchmove="drawMove($event)"
					@touchend="drawEnd($event)" :style="{ right: item.RightPadding + 'rpx' }">
					<view class="consultation_content" @click="selectConsultation(item)">
						<view class="consultation_left">
							<image :src="item.avatar || '../../static/img/ai_avatar.png'"></image>
							<view v-if="item.unreadCount > 0" class="un_read">
								{{item.unreadCount > 99 ? '99+' : item.unreadCount}}
							</view>
						</view>
						<view class="consultation_right">
							<view class="consultation_title">{{ item.title || '智能咨询' }}</view>
							<view class="consultation_preview overflow_1">{{ item.lastMessage || '开始您的智能咨询吧' }}</view>
							<view class="consultation_time">{{ formatTime(item.lastTime) }}</view>
						</view>
					</view>
					<view class="remove" @click.stop="delConsultation(item)">删除</view>
				</view>
			</block>
			<view v-else class="no_consultation">
				<view>
					<image class="no_consultation_img" src="../../static/img/noPeple.png" mode="widthFix">
					</image>
					<view>还没有咨询记录</view>
					<view class="start_tip">点击右上角"+"按钮开始智能咨询</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				startX: 0,
				delBtnWidth: 180,
				isScroll: true,
				windowHeight: 0,
			}
		},
		computed: {
			consultationList() {
				return this.$store.state.consultationList;
			}
		},
		onShow() {
			// 获取设备信息
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight;
				}
			});
			
			// 仅使用HTTP API加载咨询列表（按后端对接文档，需要带鉴权头并仅返回有用户首条消息的会话）
			this.loadConsultationListWithHTTP();
		},
		methods: {
			// 保留占位，后续若需要实时功能再启用
			initSocketIfNeeded() {},

			// 使用HTTP API加载咨询列表
			loadConsultationListWithHTTP() {
				this.$store.dispatch('fetchConsultationListAction')
					.then(consultationList => {
						console.log('成功加载咨询列表:', consultationList);
					})
					.catch(error => {
						console.error('加载咨询列表失败:', error);
						// 尝试从本地存储加载
						const storedList = uni.getStorageSync('consultationList');
						if (storedList) {
							try {
								const consultationList = JSON.parse(storedList);
								this.$store.commit('setPropName', {
									propName: 'consultationList',
									value: consultationList
								});
							} catch (e) {
								console.error('解析咨询列表失败', e);
							}
						}
					});
			},
			
			// 创建新咨询（按文档：创建成功后立即跳转到会话页，不依赖列表显示）
			createNewConsultation() {
				this.createConsultationWithHTTP();
			},
			
			// 使用HTTP API创建咨询
			createConsultationWithHTTP() {
				this.$store.dispatch('createConsultationAction')
					.then(consultation => {
						// 设置当前咨询会话
						this.$store.commit('setCurrentConsultation', consultation);
						
						// 进入新建会话后，清空当前消息列表（后续进入聊天页再拉取）
						this.$store.commit('setPropName', {
							propName: 'consultationMessages',
							value: []
						});
						
						// 设置reciver，保证聊天页面健壮
						this.$store.commit('setPropName', {
							propName: 'reciver',
							value: consultation
						});
						
						// 跳转到聊天页面
						this.$Common.navigateTo("/chatContent/chatContent");
					})
					.catch(error => {
						console.error('创建咨询失败:', error);
						this.$Common.tipMsg('创建咨询失败，请重试');
					});
			},
			
			// 本地创建咨询（备用方法）
			createConsultationLocally(consultation) {
				// 创建新咨询会话
				this.$store.commit('createConsultation', consultation);
				
				// 设置当前咨询会话
				this.$store.commit('setCurrentConsultation', consultation);
				
				// 重要：清空咨询消息列表
				this.$store.commit('setPropName', {
					propName: 'consultationMessages',
					value: []
				});
				
				// 设置reciver，保证聊天页面健壮
				this.$store.commit('setPropName', {
					propName: 'reciver',
					value: consultation
				});
				
				// 跳转到聊天页面
				this.$Common.navigateTo("/chatContent/chatContent");
			},
			
			// 选择咨询会话
			selectConsultation(item) {
				this.$store.commit('setCurrentConsultation', item);
				
				// 设置reciver，保证聊天页面健壮
				this.$store.commit('setPropName', {
					propName: 'reciver',
					value: item
				});
				
				// 从后端加载咨询消息
				this.loadConsultationMessagesFromBackend(item.id);
				
				// 跳转到聊天页面
				this.$Common.navigateTo("/chatContent/chatContent");
			},
			
			// 从后端加载咨询消息（HTTP API）
			loadConsultationMessagesFromBackend(consultationId) {
				this.loadConsultationMessagesWithHTTP(consultationId);
			},
			
			// 使用HTTP API加载咨询消息
			loadConsultationMessagesWithHTTP(consultationId) {
				this.$store.dispatch('fetchConsultationMessagesAction', consultationId)
					.then(messages => {
						console.log('成功加载咨询消息:', messages);
						// 确保当前消息列表被正确设置
						this.$store.commit('setPropName', {
							propName: 'consultationMessages',
							value: messages
						});
					})
					.catch(error => {
						console.error('加载咨询消息失败:', error);
						// 使用本地存储的消息
						this.$store.commit('loadConsultationMessages', consultationId);
					});
			},
			
			// 获取咨询消息（这里可以从本地存储或API获取）
			getConsultationMessages(consultationId) {
				// 使用consultationMessagesMap中的数据
				return this.$store.state.consultationMessagesMap[consultationId] || [];
			},
			
			// 删除咨询会话
			delConsultation(item) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个咨询会话吗？',
					success: (res) => {
						if (res.confirm) {
							// 检查socket连接
							if (!this.$store.state.socket) {
								console.error("Socket未连接，无法删除咨询");
								// 使用HTTP API删除
								this.deleteConsultationWithHTTP(item.id);
								return;
							}
							
							// 通过后端删除咨询
							this.$store.state.socket.emit("deleteConsultation", {
								consultationId: item.id,
								userId: this.$store.state.sender.Id
							});
							
							// 监听删除咨询响应
							this.$store.state.socket.once("consultationDeleted", (response) => {
								if (response && response.success) {
									// 删除本地咨询
									this.$store.commit('deleteConsultation', item.id);
								} else {
									// 如果没有收到有效响应，使用HTTP API
									this.deleteConsultationWithHTTP(item.id);
								}
							});
							
							// 设置超时，如果3秒内没有收到响应，使用HTTP API
							setTimeout(() => {
								// 检查咨询是否已被删除
								const existingIndex = this.$store.state.consultationList.findIndex(c => c.id === item.id);
								if (existingIndex > -1) {
									// 咨询还存在，使用HTTP API删除
									this.deleteConsultationWithHTTP(item.id);
								}
							}, 3000);
						}
					}
				});
			},
			
			// 使用HTTP API删除咨询
			deleteConsultationWithHTTP(consultationId) {
				this.$store.dispatch('deleteConsultationAction', consultationId)
					.then(result => {
						console.log('成功删除咨询:', result);
						// 删除本地咨询
						this.$store.commit('deleteConsultation', consultationId);
					})
					.catch(error => {
						console.error('删除咨询失败:', error);
						this.$Common.tipMsg('删除咨询失败，请重试');
					});
			},
			
			// 格式化时间
			formatTime(timeStr) {
				if (!timeStr) return '';
				const date = new Date(timeStr);
				const now = new Date();
				const diff = now - date;
				
				if (diff < 24 * 60 * 60 * 1000) {
					// 今天
					return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
				} else if (diff < 7 * 24 * 60 * 60 * 1000) {
					// 一周内
					const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
					return days[date.getDay()];
				} else {
					// 更早
					return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
				}
			},
			drawStart: function(e) {
				let touch = e.touches[0];
				for (let index in this.consultationList) {
					this.consultationList[index].RightPadding = 0;
				}
				this.startX = touch.clientX;
			},
			drawMove: function(e) {
				let touch = e.touches[0];
				let disX = this.startX - touch.clientX;
				let consultationList = this.consultationList;
				if (disX >= 20) {
					if (disX > this.delBtnWidth) {
						disX = this.delBtnWidth;
					}
					this.isScroll = false;
					consultationList[e.currentTarget.dataset.index].RightPadding = disX;
				} else {
					this.isScroll = true;
					consultationList[e.currentTarget.dataset.index].RightPadding = 0;
				}
				this.$store.commit('setPropName', {
					propName: 'consultationList',
					value: consultationList
				})
			},
			drawEnd: function(e) {
				let consultationList = this.consultationList;
				let item = consultationList[e.currentTarget.dataset.index];
				if (item.RightPadding >= this.delBtnWidth / 2) {
					this.isScroll = true;
					consultationList[e.currentTarget.dataset.index].RightPadding = this.delBtnWidth;
				} else {
					this.isScroll = true;
					consultationList[e.currentTarget.dataset.index].RightPadding = 0;
				}
				this.$store.commit('setPropName', {
					propName: 'consultationList',
					value: consultationList
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.consultation_page {
		height: 100vh;
		width: 100%;
		background-color: #f5f5f5;
		
		.page_header {
			height: 90rpx;
			width: 100%;
			background-color: #ffffff;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 30rpx;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			position: relative;
			z-index: 10;
			
			.title {
				font-size: 36rpx;
				font-weight: 600;
				color: #333;
			}
			
			.new_consultation_btn {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				background: #667eea;
				color: white;
				display: flex;
				justify-content: center;
				align-items: center;
				box-shadow: 0 4rpx 10rpx rgba(102, 126, 234, 0.3);
				
				.btn_text {
					font-size: 40rpx;
					font-weight: 500;
					line-height: 1;
				}
			}
		}

		.consultation_list {
			height: calc(100% - 90rpx);
			width: 100%;
			overflow: auto;
			padding-top: 20rpx;

			.consultation_item {
				height: 180rpx;
				width: 100%;
				position: relative;
				box-sizing: border-box;
				background: white;
				margin-bottom: 2rpx;

				.consultation_content {
					height: 100%;
					width: 100%;
					display: flex;
					padding: 20rpx;

					.consultation_left {
						width: 18%;
						height: 100%;
						display: flex;
						justify-content: center;
						align-items: center;
						position: relative;
						
						image {
							height: 100rpx;
							width: 100rpx;
							border-radius: 50%;
						}
						
						.un_read {
							display: inline-block;
							position: absolute;
							top: 8px;
							right: 2px;
							height: 20px;
							width: 20px;
							border-radius: 50%;
							line-height: 10px;
							padding: 5px;
							text-align: center;
							background: #EE593C;
							color: #fff;
							font-size: 20rpx;
						}
					}

					.consultation_right {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						padding-left: 20rpx;

						.consultation_title {
							font-size: 32rpx;
							font-weight: 500;
							color: #333;
							margin-bottom: 10rpx;
						}

						.consultation_preview {
							font-size: 28rpx;
							color: #666;
							margin-bottom: 10rpx;
						}

						.consultation_time {
							font-size: 24rpx;
							color: #999;
							align-self: flex-end;
						}
					}
				}

				.remove {
					position: absolute;
					top: 0;
					right: 0;
					width: 160rpx;
					height: 100%;
					background: #ff4757;
					color: white;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 28rpx;
				}
			}

			.no_consultation {
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;

				.no_consultation_img {
					width: 200rpx;
					height: 200rpx;
					margin-bottom: 40rpx;
				}

				view {
					font-size: 28rpx;
					color: #999;
					margin-bottom: 20rpx;
				}

				.start_tip {
					font-size: 24rpx;
					color: #ccc;
				}
			}
		}
	}

	.overflow_1 {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>
